<template>
  <div style="padding: 0 40px">
    <h3>学生证列表</h3>
    <el-form inline :model="keywords" style="display: flex">
      <el-form-item label="查找 :" style="flex: 1">
        <el-autocomplete
          class="inline-input"
          v-model="keywords.stuClass"
          :fetch-suggestions="querySearch"
          placeholder="请输入班级进行查找"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-upload
          :auto-upload="false"
          :on-change="upload"
          :show-file-list="false"
          action
        >
          <el-button slot="trigger" type="primary">上传表格数据</el-button>
          <el-button style="margin-left: 10px" type="success" @click="download"
            >下载到表格</el-button
          >
        </el-upload>
      </el-form-item>
    </el-form>
    <el-table @sort-change="sortStudent" :data="pageStudent">
      <el-table-column prop="stuId" label="学号"> </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="sex" label="性别"> </el-table-column>
      <el-table-column prop="stuClass" label="班级"> </el-table-column>
      <el-table-column prop="category" sortable="custom" label="系部">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="$router.push(`/students/edit/${scope.row.stuId}`)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="removeStudent(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: right; margin: 40px 0"
      :current-page.sync="page.currentPage"
      :page-sizes="page.pageSizes"
      :page-size.sync="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="findStudents.length"
    >
    </el-pagination>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Action, State } from "vuex-class";
import XLSX from "xlsx";

@Component
export default class EditStudent extends Vue {
  @State("studentList") studentList: any;
  @Action("delStu") delStu: any;
  @Action("initStu") initStu: any;

  keywords: any = {};
  student = {};
  page = {
    pageSize: 5,
    pageSizes: [5, 10, 20, 50],
    currentPage: 1,
  };
  sort: number = 0;

  upload(e: any) {
    const f = e.raw;
    const reader = new FileReader();
    reader.onload = async (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const total_students = XLSX.utils.sheet_to_json(worksheet);
      const students = total_students.filter((s: any) => {
        return !this.studentList.find((item: any) => item.stuId == s.stuId);
      });
      await this.$http.post(`students/more`, {
        students,
      });
      this.initStu();
      const repeat = total_students.length - students.length;
      if(repeat){
        this.$message.warning(`成功添加 ${students.length} 条, 忽略 ${repeat} 条学号重复数据`);
      }else{
        this.$message.success(`成功添加 ${students.length} 条数据`);
      }
    };
    reader.readAsArrayBuffer(f);
  }

  download() {
    const filterData = this.findStudents.map((item: any) => {
      delete item._id;
      delete item.__v;
      return item;
    });

    const worksheet = XLSX.utils.json_to_sheet(filterData);
    const new_workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(new_workbook, worksheet, "Worksheet");
    XLSX.writeFile(new_workbook, "学生证列表.xls");
  }

  querySearch(queryString: string, cb: any) {
    let classSet = new Set(this.studentList.map((item: any) => item.stuClass));
    let classList = [];
    for (let item of classSet.values()) {
      classList.push({ value: item });
    }
    cb(
      queryString ? classList.filter(this.createFilter(queryString)) : classList
    );
  }

  createFilter(queryString: any) {
    return (restaurant: any) => {
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      );
    };
  }

  sortStudent({ order }: any) {
    switch (order) {
      case "ascending":
        this.sort = 1;
        break;
      case "descending":
        this.sort = -1;
        break;
      default:
        this.sort = 0;
    }
  }

  async removeStudent(student: any) {
    await this.$http.delete(`students/${student._id}`);
    this.initStu();
    this.$message.success(`学号 ${student.stuId} 的学生证删除成功`);
  }

  get findStudents() {
    const copy_list = [...this.studentList];
    if (this.sort) {
      copy_list.sort(
        (
          { category: a }: { category: string },
          { category: b }: { category: string }
        ) => {
          return a.localeCompare(b) * this.sort;
        }
      );
    }
    if (!this.keywords.stuClass) {
      return copy_list;
    }
    return copy_list.filter(
      (item: any) => item.stuClass == this.keywords.stuClass
    );
  }

  get pageStudent() {
    const start = (this.page.currentPage - 1) * this.page.pageSize;
    return this.findStudents.slice(start, start + this.page.pageSize);
  }
}
</script>
